import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Plus, Upload, X } from 'lucide-react';

const ProductForm = ({ product, onSave, onCancel }) => {
  const [formData, setFormData] = useState({
    name: product?.name || '',
    categoryId: product?.category_id || '',
    price: product?.price?.toString() || '',
    originalPrice: product?.original_price?.toString() || '',
    stock: product?.stock?.toString() || '',
    description: product?.description || '',
    tags: product?.tags || [],
    status: product?.status || 'active'
  });
  const [newTag, setNewTag] = useState('');
  const [imageList, setImageList] = useState(product?.images || []);

  // 处理表单字段变化
  const handleFieldChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 添加标签
  const handleAddTag = () => {
    if (newTag.trim() && !formData.tags.includes(newTag.trim())) {
      setFormData(prev => ({
        ...prev,
        tags: [...prev.tags, newTag.trim()]
      }));
      setNewTag('');
    }
  };

  // 删除标签
  const handleRemoveTag = (tagToRemove) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags.filter(tag => tag !== tagToRemove)
    }));
  };

  // 处理图片上传
  const handleImageUpload = (e) => {
    const files = Array.from(e.target.files);
    const newImages = files.map(file => ({
      id: Date.now() + Math.random(),
      url: URL.createObjectURL(file),
      file: file
    }));
    setImageList(prev => [...prev, ...newImages]);
  };

  // 删除图片
  const handleRemoveImage = (imageId) => {
    setImageList(prev => prev.filter(img => img.id !== imageId));
  };

  // 表单提交
  const handleSubmit = (e) => {
    e.preventDefault();
    onSave && onSave({ ...formData, images: imageList });
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{product ? '编辑商品' : '添加商品'}</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="name">商品名称 *</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => handleFieldChange('name', e.target.value)}
                placeholder="请输入商品名称"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="category">商品分类 *</Label>
              <Select value={formData.categoryId} onValueChange={(value) => handleFieldChange('categoryId', value)}>
                <SelectTrigger>
                  <SelectValue placeholder="请选择商品分类" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="phone">手机</SelectItem>
                  <SelectItem value="laptop">笔记本</SelectItem>
                  <SelectItem value="tablet">平板</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="price">商品价格 *</Label>
              <Input
                id="price"
                type="number"
                step="0.01"
                min="0"
                value={formData.price}
                onChange={(e) => handleFieldChange('price', e.target.value)}
                placeholder="请输入商品价格"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="originalPrice">原价</Label>
              <Input
                id="originalPrice"
                type="number"
                step="0.01"
                min="0"
                value={formData.originalPrice}
                onChange={(e) => handleFieldChange('originalPrice', e.target.value)}
                placeholder="请输入原价"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="stock">库存 *</Label>
              <Input
                id="stock"
                type="number"
                min="0"
                value={formData.stock}
                onChange={(e) => handleFieldChange('stock', e.target.value)}
                placeholder="请输入库存数量"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="status">商品状态</Label>
              <Select value={formData.status} onValueChange={(value) => handleFieldChange('status', value)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="active">上架</SelectItem>
                  <SelectItem value="inactive">下架</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 商品描述 */}
          <div className="space-y-2">
            <Label htmlFor="description">商品描述</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) => handleFieldChange('description', e.target.value)}
              placeholder="请输入商品描述"
              rows={4}
            />
          </div>

          {/* 商品标签 */}
          <div className="space-y-2">
            <Label>商品标签</Label>
            <div className="flex gap-2">
              <Input
                value={newTag}
                onChange={(e) => setNewTag(e.target.value)}
                placeholder="输入标签后按回车添加"
                onKeyPress={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault();
                    handleAddTag();
                  }
                }}
              />
              <Button type="button" variant="outline" onClick={handleAddTag}>
                <Plus className="size-4" />
              </Button>
            </div>
            {formData.tags.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-2">
                {formData.tags.map((tag, index) => (
                  <Badge key={index} variant="secondary" className="gap-1">
                    {tag}
                    <button
                      type="button"
                      onClick={() => handleRemoveTag(tag)}
                      className="ml-1 hover:text-destructive"
                    >
                      <X className="size-3" />
                    </button>
                  </Badge>
                ))}
              </div>
            )}
          </div>

          {/* 商品图片 */}
          <div className="space-y-2">
            <Label>商品图片</Label>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {imageList.map((image) => (
                <div key={image.id} className="relative group">
                  <img
                    src={image.url}
                    alt="商品图片"
                    className="w-full h-24 object-cover rounded border"
                  />
                  <button
                    type="button"
                    onClick={() => handleRemoveImage(image.id)}
                    className="absolute top-1 right-1 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                  >
                    <X className="size-3" />
                  </button>
                </div>
              ))}
              {imageList.length < 8 && (
                <label className="border-2 border-dashed border-muted-foreground/25 rounded flex items-center justify-center h-24 cursor-pointer hover:border-muted-foreground/50 transition-colors">
                  <div className="text-center">
                    <Upload className="size-6 mx-auto mb-1 text-muted-foreground" />
                    <span className="text-xs text-muted-foreground">上传图片</span>
                  </div>
                  <input
                    type="file"
                    accept="image/*"
                    multiple
                    onChange={handleImageUpload}
                    className="hidden"
                  />
                </label>
              )}
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex gap-4 pt-4">
            <Button type="submit">
              {product ? '更新商品' : '添加商品'}
            </Button>
            <Button type="button" variant="outline" onClick={onCancel}>
              取消
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
};

export default ProductForm; 